/*
 * @Author: yixin 
 * @Date: 2019-12-08 19:39:40 
 * @Last Modified by: yixin
 * @Last Modified time: 2020-01-10 17:33:43
 * 车辆统计
 */
import React, { Component } from "react"
import { withRouter } from "react-router";
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/legendScroll';
import 'echarts/lib/component/dataZoom';
import 'echarts/lib/component/dataZoomInside';
import 'echarts/lib/component/tooltip';
import md5 from 'js-md5';
import styles from './statistics.less'
import { carDayOil, carMonthOil, carDayTime, carMonthTime, carDayQuantity, carDayDetail, carMonthQuantity } from '@/services'
import MonthModal from '@/components/monthModal'
import YearModal from '@/components/yearModal'
import { formatNumber } from '@/utils'

class Statistics extends Component {

  constructor(props){
    super(props);
    this.nowDate = new Date();
    this.nowYear = new Date().getFullYear();
    this.nowMonth = new Date().getMonth() + 1;
    this.state = {
      type: 0, // 0 月 1 年
      month: this.nowMonth,
      year: this.nowYear,
      carList: [],
      expandCar: 0,
    }
    this.times = {
      beginDate: `${this.nowYear}-${this.nowMonth<10 ? '0' + this.nowMonth : this.nowMonth}-01`,
      endDate: `${this.nowYear}-${this.nowMonth<10 ? '0' + this.nowMonth : this.nowMonth}-31`
    }
  }

  componentDidMount() {
    this.init()
  }

  init = async() => {
    try {
      this.renderOilChart()
      this.renderTimeChart()
      this.renderQuantityChart()
      this.renderCarDetail()
    } catch (error) {
      console.log(error)
    }
  }

  renderOilChart = async() => {
    try {
      echarts.dispose(document.getElementById('oilChart'));
      const oilData = this.state.type === 0 ? await carDayOil(this.times) : await carMonthOil(this.times)
      if(oilData.code===200){
        let company = [];
        let profess = [];
        let time = []
        oilData.data.map(data=>{
          company.push(data.company);
          profess.push(data.profess);
          time.push(data.time)
        });
        this.oilChart = echarts.init(document.getElementById('oilChart'));
        this.oilChart.setOption({
          grid: {
            top: 130,
            left: 45,
            right: 20,
          },
          tooltip: {
            trigger: 'axis',
            triggerOn: 'click',
            axisPointer: {
                type: 'shadow',
            },
            confine: true,
            formatter: params => {
              return `
              ${params[0].axisValue.slice(0,4)}年${params[0].axisValue.slice(4,6)}月${this.state.type ? '' : params[0].axisValue.slice(-2)+'日'}<br />
              ${params[0].seriesName}(L)：${(params[0].value*1).toFixed(2)}<br />
              ${params[1].seriesName}(L)：${(params[1].value*1).toFixed(2)}
              `
            }
          },
          xAxis: {
            type: 'category',
            data: time,
            nameTextStyle: {
              fontSize: 16,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              formatter: (value) => {
                return `${value.slice(-2)}${this.state.type?'月':'日'}`
              }
            }
          },
          yAxis: [{
            type: 'value',
            splitLine: {
                show: false
            },
            axisLabel: {
              formatter: '{value}L'
            }
          }],
          dataZoom: [
            {
              type:"inside",
              
              preventDefaultMouseMove: false
            }
          ],
          legend: {
            top: 73,
            left: 4,
            data: [{
              name: `行业车辆${this.state.type?'月':'日'}平均油耗`,
              icon: 'roundRect'
            },{
              name: `公司车辆${this.state.type?'月':'日'}平均油耗`
            },]
          },
          series: [
            { 
              name: `行业车辆${this.state.type?'月':'日'}平均油耗`,
              type: 'line',
              data: profess,
              showSymbol: true,
              itemStyle: {
                color: '#FF2F00',
              },
            },
            {
              name: `公司车辆${this.state.type?'月':'日'}平均油耗`,
              type: 'bar',
              data: company,
              itemStyle: {
                color: '#D0B17E'
              },
              barMaxWidth: 20,
          }
        ]
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  renderTimeChart = async() => {
    try {
      echarts.dispose(document.getElementById('timeChart'));
      const oilData = this.state.type ? await carMonthTime(this.times) : await carDayTime(this.times);
      if(oilData.code===200){
        let company = [];
        let profess = [];
        let time = []
        oilData.data.map(data=>{
          company.push((data.company/3600).toFixed(2));
          profess.push((data.profess/3600).toFixed(2));
          time.push(data.time)
        });
        this.timeChart = echarts.init(document.getElementById('timeChart'));
        this.timeChart.setOption({
          grid: {
            top: 130,
            left: 45,
            right: 20,
          },
          tooltip: {
            show: true,
            trigger: 'axis',
            triggerOn: 'click',
            axisPointer: {
              type: 'shadow'
            },
            confine: true,
            formatter: params => {
              return `
              ${params[0].axisValue.slice(0,4)}年${params[0].axisValue.slice(4,6)}月${this.state.type ? '' : params[0].axisValue.slice(-2)+'日'}<br />
              ${params[0].seriesName}(H)：${(params[0].value*1).toFixed(2)}<br />
              ${params[1].seriesName}(H)：${(params[1].value*1).toFixed(2)}
              `
            }
          },
          xAxis: {
            type: 'category',
            data: time,
            nameTextStyle: {
              fontSize: 16,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              formatter: (value) => {
                return `${value.slice(-2)}${this.state.type?'月':'日'}`
              }
            }
          },
          yAxis: [{
            type: 'value',
            splitLine: {
                show: false
            },
            axisLabel: {
              formatter: '{value}H'
            }
          }],
          dataZoom: [
            {
              type:"inside",
              preventDefaultMouseMove: false
            }
          ],
          legend: {
            top: 73,
            left: 4,
            data: [{
              name: `行业车辆${this.state.type?'月':'日'}平均工作小时`,
              icon: 'roundRect'
            },{
              name: `公司车辆${this.state.type?'月':'日'}平均工作小时`
            },]
          },
          series: [
            { 
              name: `行业车辆${this.state.type?'月':'日'}平均工作小时`,
              type: 'line',
              data: profess,
              showSymbol: true,
              itemStyle: {
                color: '#FF2F00',
              },
            },
            {
              name: `公司车辆${this.state.type?'月':'日'}平均工作小时`,
              type: 'bar',
              data: company,
              itemStyle: {
                color: '#D0B17E'
              },
              barMaxWidth: 20,
          }
        ]
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  renderQuantityChart = async() => {
    try {
      echarts.dispose(document.getElementById('quantityChart'));
      const oilData = this.state.type ? await carMonthQuantity(this.times) : await carDayQuantity(this.times);
      if(oilData.code===200){
        let company = [];
        let profess = [];
        let time = []
        oilData.data.map(data=>{
          company.push(data.company);
          profess.push(data.profess);
          time.push(data.time)
        });
        this.quantityChart = echarts.init(document.getElementById('quantityChart'));
        this.quantityChart.setOption({
          grid: {
            top: 130,
            left: 45,
            right: 20,
          },
          tooltip: {
            show: true,
            trigger: 'axis',
            triggerOn: 'click',
            axisPointer: {
                type: 'shadow'
            },
            confine: true,
            formatter: params => {
              return `
              ${params[0].axisValue.slice(0,4)}年${params[0].axisValue.slice(4,6)}月${this.state.type ? '' : params[0].axisValue.slice(-2)+'日'}<br />
              ${params[0].seriesName}(方)：${(params[0].value*1).toFixed(2)}<br />
              ${params[1].seriesName}(方)：${(params[1].value*1).toFixed(2)}
              `
            }
          },
          xAxis: {
            type: 'category',
            data: time,
            nameTextStyle: {
              fontSize: 16,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              formatter: (value) => {
                return `${value.slice(-2)}${this.state.type?'月':'日'}`
              }
            }
          },
          yAxis: [{
            type: 'value',
            splitLine: {
                show: false
            },
            axisLabel: {
              formatter: '{value}方'
            }
          }],
          dataZoom: [
            {
              type:"inside",
              preventDefaultMouseMove: false
            }
          ],
          legend: {
            top: 73,
            left: 4,
            data: [{
              name: `行业车辆${this.state.type?'月':'日'}平均泵送方量`,
              icon: 'roundRect'
            },{
              name: `公司车辆${this.state.type?'月':'日'}平均泵送方量`
            },]
          },
          series: [
            { 
              name: `行业车辆${this.state.type?'月':'日'}平均泵送方量`,
              type: 'line',
              data: profess,
              showSymbol: true,
              itemStyle: {
                color: '#FF2F00',
              },
            },
            {
              name: `公司车辆${this.state.type?'月':'日'}平均泵送方量`,
              type: 'bar',
              data: company,
              itemStyle: {
                  color: '#D0B17E'
              },
              barMaxWidth: 20,
          }
        ]
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  renderCarDetail = async () => {
    try {
      const oilData = await carDayDetail(this.times)
      if(oilData.code===200){
        this.setState({
          carList: oilData.data
        })
      }
    } catch (error) {
      
    }
  }

  handleChangeType = (type) => {
    this.times = {
      beginDate: type === 0 ? `${this.nowYear}-${this.nowMonth<10 ? '0' + this.nowMonth : this.nowMonth}-01` : `${this.nowYear}-01-01`,
      endDate: type === 0 ? `${this.nowYear}-${this.nowMonth<10 ? '0' + this.nowMonth : this.nowMonth}-31` : `${this.nowYear}-12-31`
    }
    this.setState({ 
      type: type,
      month: Number((this.times.beginDate.split('-'))[1]),
      year: Number((this.times.beginDate.split('-'))[0]),
    },this.init)
  }

  chooseOtherDate = (date) =>{
    try {
      this.times = date;
      this.setState({ month: Number((date.beginDate.split('-'))[1]), year: Number((date.beginDate.split('-'))[0]) });
      this.dateModal && this.dateModal.dismiss();
      this.yearModal && this.yearModal.dismiss();
      this.init()
    } catch (error) {
      console.log(error)
    }
  }

  toCarDetail = (equipCode) => {
    this.props.history.push(`carDetail?equipCode=${equipCode}&source=selfpage&token=${md5(equipCode+'selfpage'+'s$31d0dl1!~93-kHj^S')}`)
  }
  
  render(){
    const { type, month, year } = this.state;
    return (
      <div className={styles.statistics}>
        <div className={styles.header}>
          <img onClick={()=>{ this.props.history.goBack() }} className={styles.back} src={require('../assets/img/back.png')} />
          <div className={styles.option}>
            <div onClick={()=>{ this.handleChangeType(0) }} className={`${styles.option_item} ${type==0 && styles.option_item_active}`}>月统计</div>
            <div onClick={()=>{ this.handleChangeType(1) }} className={`${styles.option_item} ${type==1 && styles.option_item_active}`}>年统计</div>
          </div>
          <div className={styles.month} onClick={()=>{ type === 0 ? (this.dateModal && this.dateModal.show()) : (this.yearModal && this.yearModal.show()) }}>{type === 0 ? `${month}月` : `${year}年`} 
          <img src={require('../assets/img/down.png')} className={styles.icon_down} /></div>
        </div>
        <div className={styles.chart}>
          <div className={styles.chart_title}>车辆{this.state.type?'月':'日'}平均油耗统计</div>
          <div className={styles.chart_oil} id="oilChart"></div>
        </div>
        <div className={styles.chart}>
          <div className={styles.chart_title}>车辆{this.state.type?'月':'日'}平均工作时间统计</div>
          <div className={styles.chart_oil} id="timeChart"></div>
        </div>
        <div className={styles.chart}>
          <div className={styles.chart_title}>车辆{this.state.type?'月':'日'}平均泵送方量统计</div>
          <div className={styles.chart_oil} id="quantityChart"></div>
        </div>
        <div className={styles.car}>
          <div className={styles.car_title}>车辆工作详情</div>
          <div className={styles.car_list}>
            {
              this.state.carList.map((car, index)=>(
                index == this.state.expandCar ? 
                (<div key={car.equipCode} className={styles.car_item__expand}>
              <div className={styles.expand_title}>
                <div className={styles.expand_text}>{car.equipCode}</div>
                <div className={styles.expand_chart} onClick={()=>{ this.toCarDetail(car.equipCode) }}>图表</div>
              </div>
              <div className={styles.expand_inform}>
                <div className={styles.inform_row}>
                  <div className={styles.row_item}>泵送量：{formatNumber(car.quantityNum)}方</div>
                  <div className={styles.row_item}>泵送计时：{formatNumber(car.pumpDuration/3600)}H</div>
                </div>
                <div className={styles.inform_row}>
                  <div className={styles.row_item}>总油耗：{formatNumber(car.oilNum)}L</div>
                  <div className={styles.row_item}>方量油耗：{formatNumber(car.oilPerQuantity)}L/方</div>
                </div>
                <div className={styles.up} onClick={()=>{ this.setState({ expandCar: 999 }) }}>
                  <img className={styles.up_icon} src={require('../assets/img/project/up.png')} />
                  收起
                </div>
              </div>
            </div>) : <div onClick={()=>{ this.setState({ expandCar: index }) }} key={car.equipCode} className={styles.car_item}>
              {car.equipCode}
            </div>
              ))
            }
          </div>
        </div>
        <MonthModal submit={this.chooseOtherDate} ref={ el => { this.dateModal = el }} />
        <YearModal submit={this.chooseOtherDate} ref={ el => { this.yearModal = el }} />
      </div>
    )
  }
}
export default withRouter(Statistics)